//-----------------------------------------------------------
// Android SDL Sample App
//
// Copyright (c) 2015 Zebra Technologies
//-----------------------------------------------------------

package com.zebra.sdl;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Timer;
import java.util.TimerTask;

import com.zebra.adc.decoder.BarCodeReader;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources.NotFoundException;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.ImageFormat;
import android.graphics.Matrix;
import android.graphics.PixelFormat;
import android.jb.Preference;
import android.media.AudioManager;
import android.media.ToneGenerator;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.CompoundButton.OnCheckedChangeListener;

import com.barcode.BeepManager;
import com.barcode.ScanActivity;
import com.barcode.ScanListAdapter;
import com.zebra.sdl.SdlScanListener;
import com.zebra.sdl.SdlScanSetupActivity;
import com.codecorp.cortex_scan.InformationActivity;
import com.codecorp.cortex_scan.SettingsActivity;
import com.zebra.sdl.SdlScanService.MyBinder;
import com.main.BaseApplication;
import com.main.EditTextDialog;
import com.example.ht380d4G_jar_demo.R;

public class SDLguiActivity extends Activity implements BarCodeReader.PictureCallback, BarCodeReader.PreviewCallback,
		SurfaceHolder.Callback, /*BarCodeReader.VideoCallback, */SdlScanListener
{
	// ------------------------------------------------------
	static final private boolean saveSnapshot = false; // true = save snapshot to file
	private static final int SIMULATE_TYPE = 2;
	private static final int SEND_TYPE = 3;
	private static final int QUICK_TYPE = 1;
	private static final String TAG = "SDLgui";
	static private boolean sigcapImage = true; // true = display signature capture
	static private boolean videoCapDisplayStarted = false;

	public BeepManagerSdl mBeepManagersdl;
	private static File ss=new File("/proc/jbcommon/gpio_control/se4710");

	Intent service;
	// -----------------------------------------------------
	// statics
	static SDLguiActivity app = null;

	// -----------------------------------------------------
	// ui
	private TextView tvStat = null;
	private TextView tvData = null;
	private EditText edPnum = null;
	private EditText edPval = null;
	private CheckBox chBeep = null;
	private CheckBox chBeep_RP 				= null;
    private CheckBox hfBox;
	private ImageView image 					= null;	//snaphot image screen
	
	
	// system
	private ToneGenerator tg 		= null;

	// BarCodeReader specifics
	private BarCodeReader bcr 		= null;

	public boolean beepMode 		= false; 		// decode beep enable
	private int Mobile_reading_pane	= 716; 		// Mobile Phone reading Pane
	private int reading_pane_value  = 1; 
	private boolean snapPreview 	= false;		// snapshot preview mode enabled - true - calls viewfinder which gets handled by 
	private int trigMode			= BarCodeReader.ParamVal.LEVEL;
	private boolean atMain			= false;
	private WakeLock mWakeLock = null;

	private int motionEvents 		= 0;
	private int modechgEvents 	= 0;
	
	private int snapNum				= 0;		//saved snapshot #
	private String decodeDataString;
	private String decodeStatString;
	private static int decCount = 0;
	private CheckBox continueCb;
    private Button  buttonDec;
	private EditTextDialog etD;
	public long intervalTime = 300;
	private int scan_time_limit = 100;
	private Intent scanDataIntent;
	private Intent EditTextintent;
	boolean bind = false;
	private SdlScanService scanService;
	private ScanListAdapter adapter;
	private ListView lv;
	// ------------------------------------------------------
	public SDLguiActivity()
	{
		app = this;
	}
	
	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			
			switch (msg.what) {
			case 1:
				
			}
		}
		
	};

	// ------------------------------------------------------
	// Called with the activity is first created.
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		mainScreen();
		String proName=BaseApplication.getProperty("ro.product.name","JB-HT368D");
		System.out.println("ceshiSDL");
		Log.v(TAG,"proName: "+proName);
		if(proName.equals("JB-HT368D")||proName.equals("LSE-P100W/G")){
			setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE); 
		}else if(proName.equals("HT380K")){
			
		}
		//setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  
	}
	
	ServiceConnection serviceConnection = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
					bind = false;
					Log.v(TAG,"SDLActivity onServiceDisconnected "+bind);
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			bind = true;
			MyBinder myBinder = (MyBinder) service;
			scanService = myBinder.getService();
			//
			scanService.setOnScanListener(SDLguiActivity.this);
			scanService.setActivityUp(true);
			Log.v(TAG,"SDLActivity onServiceConnected "+bind);
		}
	};

	//-----------------------------------------------------
	@Override
	protected void onPause()
	{
		Log.v(TAG,"SDLActivity onpause bind--->: "+bind);
		super.onPause();
		//scanService.release();
		if(scanService !=null)
		scanService.setActivityUp(false);
		releaseWakeLock();
		Log.v(TAG,"<----SDLActivity onpause bind: "+bind);
	}

	private synchronized static  void writeFile(File file, String value) {

		try {
			FileOutputStream outputStream = new FileOutputStream(file);
			outputStream.write(value.getBytes());
			outputStream.flush();
			outputStream.close();

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	// ------------------------------------------------------
	// Called when the activity is about to start interacting with the user.
	@Override
	protected void onResume()
	{
		Log.v(TAG,"SDLActivity onResume bind: "+bind);
		beepMode = Preference.getScanSound(this,false);
		chBeep.setChecked(beepMode);
		hfBox.setChecked(Preference.getBoxchecked(this,false));
		try{
			service = new Intent(this, SdlScanService.class);
			
			bindService(service, serviceConnection, BIND_AUTO_CREATE);
			startService(service);
	      }catch(Exception e){
		    Log.e("SDLguiActivity","Exceptionss: "+e+" mBeepManagersdl: "+mBeepManagersdl);
	      }
		try {
			dspStat(getResources().getString(R.string.app_name) + " v" + this.getPackageManager().getPackageInfo(this.getPackageName(), 0).versionName);
		} catch (NotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NameNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		if (scanService != null)
			scanService.setActivityUp(true);
		acquireWakeLock();
		super.onResume();
	}

// === Android UI methods =======================================
	//-----------------------------------------------------
	// create main screen
	private void mainScreen()
	{
		if (atMain)
			return;
	
		atMain = true;
		
		setContentView(R.layout.main);		// Inflate our UI from its XML layout description.

		// Hook up button presses to the appropriate event handler.
		((Button) findViewById(R.id.buttonDec)).setOnClickListener(mDecodeListener);
		((Button) findViewById(R.id.buttonHF)).setOnClickListener(mHandsFreeListener);
		hfBox = ((CheckBox) findViewById(R.id.buttonHF1));
		hfBox.setOnCheckedChangeListener(mcheckedHandsFreeListener);		
		((Button) findViewById(R.id.buttonSnap)).setOnClickListener(mSnapListener);
		((Button) findViewById(R.id.buttonSnap)).setVisibility(View.GONE);
		((Button) findViewById(R.id.buttonVid)).setOnClickListener(mVidListener);
		((Button) findViewById(R.id.buttonVid)).setVisibility(View.GONE);
		((Button) findViewById(R.id.buttonGet)).setOnClickListener(mGetParamListener);
		((Button) findViewById(R.id.buttonSet)).setOnClickListener(mSetParamListener);
		((Button) findViewById(R.id.buttonDfl)).setOnClickListener(mDflParamListener);
		((Button) findViewById(R.id.buttonProp)).setOnClickListener(mPropListener);
		((Button) findViewById(R.id.buttonEnable)).setVisibility(View.GONE);
		((Button) findViewById(R.id.buttonEnable)).setOnClickListener(mEnableAllListener);
		((Button) findViewById(R.id.buttonDisable)).setVisibility(View.GONE);
		((Button) findViewById(R.id.buttonDisable)).setOnClickListener(mDisableAllListener);
		//((Button) findViewById(R.id.buttonDecImage)).setOnClickListener(mGetDecodedImageListener);
		//((CheckBox) findViewById(R.id.checkReadingPane)).setOnClickListener(mCheckReadingPaneListener);
		
		// ui items
		tvStat = (TextView) findViewById(R.id.textStatus);
		tvData = (TextView) findViewById(R.id.textDecode);
		edPnum = (EditText) findViewById(R.id.editPnum);
		edPval = (EditText) findViewById(R.id.editPval);
		chBeep = (CheckBox) findViewById(R.id.checkBeep);
		chBeep.setVisibility(View.GONE);
		chBeep.setOnClickListener(mCheckBeepListener);
		//chBeep.setChecked(beepMode);
		
		//chBeep_RP = (CheckBox) findViewById(R.id.checkReadingPane);
		//chBeep_RP.setChecked(false);
		adapter = new ScanListAdapter(this);
		lv = (ListView) findViewById(R.id.scan_lv);
		lv.setAdapter(adapter);
	}

	//-----------------------------------------------------	
	// create snapshot image screen
//	private void snapScreen(Bitmap bmSnap)
//	{
//		atMain = false;
//		setContentView(R.layout.image);
//
//		image = (ImageView) findViewById(R.id.snap_image);		
//		image.setOnClickListener(mImageClickListener);
//		
//		if (bmSnap != null)
//			image.setImageBitmap(bmSnap);
//	}
	
//-----------------------------------------------------
	// SurfaceHolder callbacks	
//	public void surfaceCreated(SurfaceHolder holder)
//	{
//		if (state == STATE_PREVIEW)
//   		{
//				//bcr.setPreviewDisplay(holder);
//				bcr.startViewFinder(this);			//snapshot with preview mode
//   		}
//   		else //must be video	
//   		{
//				//bcr.setPreviewDisplay(holder);
//				//bcr.startVideoCapture(this);			
//   				bcr.startPreview();
//   		}
//	}
//
//	//-----------------------------------------------------
//	public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
//	{
//	}
//
//	//-----------------------------------------------------
//	public void surfaceDestroyed(SurfaceHolder holder)
//	{
//	}
	
	// ------------------------------------------------------
	// Called when your activity's options menu needs to be created.
	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		MenuItem menuItem;
        menuItem = menu.add(Menu.NONE, R.id.menu_about, 0, R.string.prop);
        menuItem.setIcon(android.R.drawable.ic_dialog_info);
        menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        menuItem = menu.add(Menu.NONE, R.id.menu_settings, 3, R.string.settings);
        menuItem.setIcon(R.drawable.ic_menu_settings_alpha);
        menuItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
        return super.onCreateOptionsMenu(menu);
	}

	// ------------------------------------------------------
	// Called right before your activity's option menu is displayed.
	@Override
	public boolean onPrepareOptionsMenu(Menu menu)
	{
		super.onPrepareOptionsMenu(menu);

		return true;
	}

	// ------------------------------------------------------
	// Called when a menu item is selected.
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == R.id.menu_settings) {
            // Launch the preferences activity
            Intent intent = new Intent();
            intent.setClass(this, SdlScanSetupActivity.class);
            startActivity(intent);
            return true;
        } else if (item.getItemId() == R.id.menu_about) {
            // Launch the information activity
//            Intent intent = new Intent();
//            intent.setClass(this, InformationActivity.class);
//            startActivity(intent);
        	if(scanService!=null)
        	doGetProp();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }
    }

	// ----------------------------------------
			// get properties
			public void doGetProp()
			{
				scanService.setIdle();
				String sMod = scanService.getStrProperty(BarCodeReader.PropertyNum.MODEL_NUMBER).trim();
				String sSer = scanService.getStrProperty(BarCodeReader.PropertyNum.SERIAL_NUM).trim();
				String sImg = scanService.getStrProperty(BarCodeReader.PropertyNum.IMGKIT_VER).trim();
				String sEng = scanService.getStrProperty(BarCodeReader.PropertyNum.ENGINE_VER).trim();
				String sBTLD = scanService.getStrProperty(BarCodeReader.PropertyNum.BTLD_FW_VER).trim();
				
				int buf = scanService.getNumProperty(BarCodeReader.PropertyNum.MAX_FRAME_BUFFER_SIZE);
				int hRes = scanService.getNumProperty(BarCodeReader.PropertyNum.HORIZONTAL_RES);
				int vRes = scanService.getNumProperty(BarCodeReader.PropertyNum.VERTICAL_RES);

				String s = "Model:\t\t" + sMod + "\n";
				s += "Serial:\t\t" + sSer + "\n";
				s += "Bytes:\t\t" + buf + "\n";
				s += "V-Res:\t\t" + vRes + "\n";
				s += "H-Res:\t\t" + hRes + "\n";
				s += "ImgKit:\t\t" + sImg + "\n";
				s += "Engine:\t" + sEng + "\n";
				s += "FW BTLD:\t" + sBTLD + "\n";
				
				AlertDialog.Builder dlg = new AlertDialog.Builder(this);
				if (dlg != null)
				{
					dlg.setTitle("SDL Properties");
					dlg.setMessage(s);
					dlg.setPositiveButton("ok", null);
					dlg.show();
				}
			}
	// ------------------------------------------------------
	// callback for beep checkbox
	OnClickListener mCheckBeepListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			beepMode = ((CheckBox) v).isChecked();
			scanService.setPlayBeep(beepMode);
		}
	};

	// ------------------------------------------------------
		// callback for beep checkbox
		OnClickListener mCheckReadingPaneListener = new OnClickListener()
		{
			public void onClick(View v)
			{

				if ( ((CheckBox) v).isChecked() )
				{
					chBeep_RP.setChecked(true);	
					reading_pane_value = 1;
					bcr.setParameter(Mobile_reading_pane, reading_pane_value);
					dspStat("Enabled mobile Phone Reading Pane");
				}
				else
				{
					chBeep_RP.setChecked(false);
					reading_pane_value = 0;
					bcr.setParameter(Mobile_reading_pane, reading_pane_value);
					dspStat("Disabled mobile Phone Reading Pane");
				}
			}
		};

	
	// ------------------------------------------------------
	// callback for decode button press
	OnClickListener mDecodeListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			scanService.doDecode();
		}
	};

	// ------------------------------------------------------
	// callback for HandsFree button press
	OnClickListener mHandsFreeListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			scanService.doHandsFree();
		}
	};

	OnCheckedChangeListener mcheckedHandsFreeListener = new OnCheckedChangeListener(){

		@Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			// TODO Auto-generated method stub
			if(isChecked &&!Preference.getBoxchecked(SDLguiActivity.this, false)){
				String s = getString(R.string.scan_continuse_scan_set);
				s = String.format(s, ""+scan_time_limit);
				etD = new EditTextDialog(SDLguiActivity.this,
						s,
						getString(R.string.scan_continue_start_scan),
						getString(R.string.cancel),
						new EditTextDialog.ClickListener() {

							@Override
							public boolean onBtn2Click(View v, String etStr) {
								// TODO Auto-generated method stub
								etD.dismiss();
								hfBox.setChecked(false);
								Preference.setBoxchecked(SDLguiActivity.this, false);
								return true;
							}
							@Override
							public boolean onBtn1Click(View v, String etStr) {
								// TODO Auto-generated method stub
								try {
									intervalTime = Long.parseLong(etStr);								
								} catch (NumberFormatException e) {
									// TODO: handle exception
									intervalTime = 200;
									e.printStackTrace();
								}
								Preference.setBoxchecked(SDLguiActivity.this, true);
								scanService.Barcode_Continue_Start(intervalTime);
								etD.dismiss();
								return true;
							}
						});
				etD.show();
			}else if(!isChecked){
				hfBox.setChecked(false);
//				stopTimer();
				Preference.setBoxchecked(SDLguiActivity.this, false);
				scanService.Barcode_Continue_Stop();
				scanService.setIdle();			
			}
			
		}
	};
	
//	Timer timer = new Timer();
//	TimerTask task = new TimerTask(){
//
//		@Override
//		public void run() {
//			// TODO Auto-generated method stub
//			Message message = new Message();
//			message.what = 1;
//			handler.sendMessage(message);
//		}		
//	};
	
//	private void stopTimer(){    
//        if (timer != null) {    
//        	timer.cancel();    
//        	timer = null;    
//        } 
//        if (task !=null) {
//        	task.cancel();    
//        	task = null;
//        }
//	}
     Handler handler = new Handler() {  
	        public void handleMessage(Message msg) {  
	            if (msg.what == 1) {  
	            	Log.v(TAG,""+System.currentTimeMillis());
	            	scanService.doDecode();		
	            }  
	            super.handleMessage(msg);  
	        };  
     };	  
	// ------------------------------------------------------
	// callback for snapshot button press
	OnClickListener mSnapListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			scanService.doSnap();
		}
	};

	// ------------------------------------------------------
	// callback for video button press
	OnClickListener mVidListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			scanService.doVideo();
		}
	};

	// ------------------------------------------------------
	// callback for properties button press
	OnClickListener mPropListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			scanService.doGetProp();
		}
	};

	// ------------------------------------------------------	
	// callback for take-picture button on snap-preview screen
	OnClickListener mTakePicListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			scanService.doSnap1();
		}
	};
	
	// ------------------------------------------------------
	// callback for video screen click
//	OnClickListener mImageClickListener = new OnClickListener()
//	{
//		public void onClick(View v)
//		{
//			setIdle();
//			mainScreen();
//		}
//	};

	// ------------------------------------------------------
	// callback for decode button press
	OnClickListener mDflParamListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			AlertDialog.Builder ad = new AlertDialog.Builder(app);		
	       ad.setMessage("Default ALL Parameters?")
	       .setCancelable(false)
	       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	               scanService.doDefaultParams();
	           }
	       })
	       .setNegativeButton("No", new DialogInterface.OnClickListener() {
	       public void onClick(DialogInterface dialog, int id) {
	           //just ignore it
	          }
	      });

	      Dialog dlg = ad.create();
			dlg.show();
		}
	};

	// ------------------------------------------------------
	// callback Get Param for button press
	OnClickListener mGetParamListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			getParam();
		}
	};

	// ------------------------------------------------------
	// callback enable all parameters for button press
	OnClickListener mEnableAllListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			dspStat("All Paramters Enabled");
			scanService.enableAllCodeTypes();
			/*String FilePath = "/mnt/sdcard/CAABVS00-002-R01D0.DAT";
			 
			boolean fIgnoreRelString = true;
			boolean fIgnoreSignature = false;
			
			int Status = bcr.FWUpdate(FilePath, fIgnoreRelString, fIgnoreSignature);

			if (Status == 0)
				dspStat("All Paramters Enabled\nFW Update Successful");
			else
				dspStat("All Paramters Enabled\nFW Update Unsuccessful");*/
		}
	};
	
	// ------------------------------------------------------
	// callback Disable all parameters for button press
	OnClickListener mDisableAllListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			dspStat("All Paramters Disabled");
			scanService.disableAllCodeTypes();
		}
	};
	
	// ------------------------------------------------------
	// callback Get Last Decoded image for button press
//	OnClickListener mGetDecodedImageListener = new OnClickListener()
//	{
//		public void onClick(View v)
//		{
//			//dspErr("LastImageDecodeComplete called");
//			byte[] data = bcr.getLastDecImage();
//			
//			//String temp = "length " + data.length + " ";
//			//dspStat(temp);
//				
//			if (data == null)
//			{
//				dspErr("LastImageDecodeComplete: data null - no image");
//			}
//						
//			// display snapshot		
//			Bitmap bmSnap = BitmapFactory.decodeByteArray(data, 0, data.length);
//			snapScreen(bmSnap);
//			
//			if (bmSnap == null)
//			{
//				dspErr("LastImageDecodeComplete: no bitmap");
//							
//			}
//			image.setImageBitmap(bmSnap);
//			
//		}
//	};
	
	// ------------------------------------------------------
	// callback for Set Param button press
	OnClickListener mSetParamListener = new OnClickListener()
	{
		public void onClick(View v)
		{
			setParam();
		}
	};

	// ----------------------------------------
	// display status string
	public void dspStat(String s)
	{
		//Log.v(TAG,"dspStat " + s);
		tvStat.setText(s);
	}

	// ----------------------------------------
	// display status resource id
	public void dspStat(int id)
	{
		tvStat.setText(id);
	}

	// ----------------------------------------
	// display error msg
	private void dspErr(String s)
	{
		tvStat.setText("ERROR" + s);
	}

	// ----------------------------------------
	// display status string
	public void dspData(String s)
	{
		//Log.v(TAG,"dspData " + s);
		if (s != null && s.length()>0) {
			if (adapter != null) {
				adapter.addStr(s);
			}
		}
		if (adapter != null) {
			adapter.notifyDataSetChanged();
			lv.setSelection(adapter.getCount() - 1);
		}
		//tvData.setText(s);
	}

	// ----------------------------------------
	private void getParam()
	{
		// get param #
		String s = edPnum.getText().toString();
		try
		{
			int num = Integer.parseInt(s);
			int val =scanService.doGetParam(num);
			if (val != BarCodeReader.BCR_ERROR)
			{
				dspStat("Get # " + num + " = " + val);
				edPval.setText(Integer.toString(val));
			}
			else
			{
				dspStat("Get # " + num + " FAILED (" + val + ")");
				edPval.setText(Integer.toString(val));
			}
		}
		catch (NumberFormatException nx)
		{
			dspStat("value ERROR");
		}
	}

	// ----------------------------------------
	private void setParam()
	{		
		// get param #
		String sn = edPnum.getText().toString();
		String sv = edPval.getText().toString();
		try
		{
			int num = Integer.parseInt(sn);
			int val = Integer.parseInt(sv);
			scanService.doSetParam(num, val);
		}
		catch (NumberFormatException nx)
		{
			dspStat("value ERROR");
		}
	}
	
	// ----------------------------------------
	// reset Level trigger mode
	void resetTrigger()
	{
		scanService.doSetParam(BarCodeReader.ParamNum.PRIM_TRIG_MODE, BarCodeReader.ParamVal.LEVEL); 
		trigMode = BarCodeReader.ParamVal.LEVEL;		
	}
			
	// ----------------------------------------
	// ----------------------------------------
	public void onPictureTaken(int format, int width, int height, byte[] abData, BarCodeReader reader)
	{
		if ( image == null)
			return;			

		// display snapshot		
		Bitmap bmSnap = BitmapFactory.decodeByteArray(abData, 0, abData.length);
		if (bmSnap == null)
		{
			dspErr("OnPictureTaken: no bitmap");
			return;			
		}
		image.setImageBitmap(rotated(bmSnap));
	
		// Save snapshot to the SD card
		if (saveSnapshot)
		{
			String snapFmt = "bin";			
			switch (bcr.getNumParameter(BarCodeReader.ParamNum.IMG_FILE_FORMAT))
			{
			case BarCodeReader.ParamVal.IMG_FORMAT_BMP:
				snapFmt = "bmp";
				break;
			
			case BarCodeReader.ParamVal.IMG_FORMAT_JPEG:
				snapFmt = "jpg";				
				break;
			
			case BarCodeReader.ParamVal.IMG_FORMAT_TIFF:
				snapFmt = "tif";	
				break;
			}
			
			File filFSpec = null;
			try
			{
				String strFile = String.format("se4500_img_%d.%s", snapNum, snapFmt);
				File filRoot = Environment.getExternalStorageDirectory();
				File filPath = new File(filRoot.getAbsolutePath() + "/DCIM/Camera");
				filPath.mkdirs();
				filFSpec = new File(filPath, strFile);
				FileOutputStream fos = new FileOutputStream(filFSpec);
				fos.write(abData);
				fos.close();
				
				++snapNum;
			}
			catch (Throwable thrw)
			{
				dspErr("Create '" + filFSpec.getAbsolutePath() + "' failed");
				dspErr("Error=" + thrw.getMessage());
			}
		}
	}
	
	// ----------------------------------------
	public void onPreviewFrame(byte[] data, BarCodeReader bcreader)
	{
	}

	

	// ----------------------------------------
	public void onEvent(int event, int info, byte[] data, BarCodeReader reader)
	{
		switch (event)
		{
		case BarCodeReader.BCRDR_EVENT_SCAN_MODE_CHANGED:
			++modechgEvents;
			dspStat("Scan Mode Changed Event (#" + modechgEvents + ")");
			break;

		case BarCodeReader.BCRDR_EVENT_MOTION_DETECTED:
			++motionEvents;
			dspStat("Motion Detect Event (#" + motionEvents + ")");
			break;
			
		case BarCodeReader.BCRDR_EVENT_SCANNER_RESET:
			dspStat("Reset Event");
			break;

		default:
			// process any other events here
			break;
		}
	}

	//-------------------------------------------------------
	private Bitmap rotated(Bitmap bmSnap)
	{
		Matrix matrix = new Matrix();
		if (matrix != null)
		{
			matrix.postRotate(90); 	  
			// create new bitmap from orig tranformed by matrix  
			Bitmap bmr = Bitmap.createBitmap(bmSnap , 0, 0, bmSnap.getWidth(), bmSnap.getHeight(), matrix, true);
			if (bmr != null)
				return bmr;
		}

		return bmSnap;		//when all else fails
	}

//	public void onVideoFrame(int format, int width, int height, byte[] data,
//			BarCodeReader reader) {
//		// display snapshot		
//		Bitmap bmSnap = BitmapFactory.decodeByteArray(data, 0, data.length);
//		
//		if(videoCapDisplayStarted == false)
//		{
//			atMain = false;
//			videoCapDisplayStarted = true;
//			setContentView(R.layout.image);
//			image = (ImageView) findViewById(R.id.snap_image);		
//			
//			// This handles snapshot with viewfinder
//			if(state == STATE_PREVIEW)
//			{
//				controlInflater = LayoutInflater.from(getBaseContext());
//				View viewControl = controlInflater.inflate(R.layout.control, null);
//				LayoutParams layoutParamsControl = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
//				this.addContentView(viewControl, layoutParamsControl);
//				((Button) findViewById(R.id.takepicture)).setOnClickListener(mTakePicListener);
//			}
//			else
//			{
//				image.setOnClickListener(mImageClickListener);
//			}
//		}
//		
//		if (bmSnap != null)
//			image.setImageBitmap(bmSnap);		
//	}

	public void onError(int error, BarCodeReader reader) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void henResult(String codeType, String context) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void result(String content) {
		// TODO Auto-generated method stub
		
	}

		//-----------------------------------------------------
		// SurfaceHolder callbacks	
		public void surfaceCreated(SurfaceHolder holder)
		{
			scanService.startViewFinder();
		}

		//-----------------------------------------------------
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height)
		{
		}

		//-----------------------------------------------------
		public void surfaceDestroyed(SurfaceHolder holder)
		{
		}

	  public void acquireWakeLock() {
		    if (mWakeLock == null) {
		         PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
		         mWakeLock = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "ZHENGYI.WZY");
	           }
		         if (mWakeLock != null) {
		        	  mWakeLock.acquire();
		            }
		    }

	 public void releaseWakeLock() {
		        if (mWakeLock != null) {
		            mWakeLock.release();
		        }
		    }	
		
	@Override
	public void onDestroy(){
		super.onDestroy();
		if (bind) {
			if (!Preference.getScanSelfopenSupport(this, true)) {
				this.stopService(service);
			}
			unbindService(serviceConnection);
			scanService=null;
//			if(BaseApplication.getProperty("ro.product.name","JB-HT368D").equals("HT380K")){
//			setResult(RESULT_OK);
//			}
		}
		}
}//end-class
